package com.basejace.system.controller;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.basejace.common.model.PubControl;
import com.basejace.common.model.PubDictdata;
import com.basejace.common.model.PubDictgroup;
import com.basejace.core.R;
import com.basejace.core.base.BaseController;
import com.basejace.core.sequence.Sequence;
import com.jfinal.plugin.activerecord.Db;

public class DictgroupController extends BaseController {

	public DictgroupController(){
		setModelClass(PubDictgroup.class);
	}
	
	public void main(){
		render("main.jsp");
	}
	
	public void show() {
		render("tree.jsp");
	}
	
	public void tree() {
		List<PubDictgroup> dictgroup = PubDictgroup.dao.find("select * from pub_dictgroup order by priority desc");
		JSONArray ao = new JSONArray();
		for (int i = 0; i < dictgroup.size(); i++) {
			JSONObject obj = new JSONObject();
			obj.put("id", dictgroup.get(i).getDictgroupid());
			Long pid = dictgroup.get(i).getDictgrouppid();
			obj.put("parent", pid == -1L ? "#" : pid.toString());
			obj.put("text", dictgroup.get(i).getGroupname() + "-" + dictgroup.get(i).getGroupcode());
			
			JSONObject li_attr = new JSONObject();
			li_attr.put("fixed", dictgroup.get(i).getFixed());
			obj.put("li_attr", li_attr);
			/*if (controls.get(i).getControlid().equals("00")) {
				Map<String,Object> openstate = new HashMap<String,Object>();
				openstate.put("opened", true);
				obj.put("state", new JSONObject(openstate));
			}*/
			
			if (1 == dictgroup.get(i).getGrouptype()) {
				obj.put("icon", "fa fa-folder icon-state-warning icon-lg");
			} else if (2 == dictgroup.get(i).getGrouptype()) {
				obj.put("icon", "fa fa-file icon-state-warning icon-lg");
			} 
			ao.add(obj);
		}
		
		renderJson(ao);
	}
	
	
	public void beforeAdd() throws Exception {
		Long dictgrouppid = getParaToLong("id");
		Long dictgroupid = Sequence.getSequence(); 
		this.getModelEntity().set("dictgroupid", dictgroupid);
		this.getModelEntity().set("dictgrouppid", dictgrouppid);
		setAttr(this.getModelSimpleName(), this.getModelEntity());
	}
	
	public void delete () {
		//TODO 还要连带删除数据字典
		try {
			this.beforeDelete();
			Object[] primaryKeys = getPK(getPara(R.Key.PK)); //可能有多组主键
			for (int i=0; i<primaryKeys.length; i++) {
				PubDictgroup model = PubDictgroup.dao.findById(primaryKeys[i]);
				Db.update("delete from pub_dictdata where groupcode=?", model.getGroupcode());
				PubDictgroup.dao.deleteById(primaryKeys[i]);
//				或者使用下面这句
//				Db.deleteById(getTableName(getModelClass()), getTablePrimaryKey(getModelClass()), primaryKeys[i]);
				
			}
			this.afterDelete();
		} catch (Exception e) {
			e.printStackTrace();
			setAttr("message", "删除失败：" + e.getMessage());
		}
		setAttr(MSG, "删除成功");
		render("tree.jsp");
	}
}
